import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Box,
  Typography,
  Paper,
  Divider,
  TextField,
  Button,
  Alert,
  List,
  ListItem,
  ListItemText,
  FormControlLabel,
  Switch
} from '@mui/material';

/**
 * I18n测试组件
 * 
 * 用于测试和调试国际化功能，检查翻译键是否存在，显示翻译状态等
 */
const I18nTester: React.FC = () => {
  const { t, i18n } = useTranslation();
  const [translationKey, setTranslationKey] = useState('patterns.categories.creational');
  const [translationResult, setTranslationResult] = useState<string>('');
  const [error, setError] = useState<string | null>(null);
  const [showDebugInfo, setShowDebugInfo] = useState(false);
  const [recentKeys, setRecentKeys] = useState<string[]>([]);
  
  // i18n资源信息
  const [resourceInfo, setResourceInfo] = useState({
    languages: i18n.languages,
    currentLanguage: i18n.language,
    namespaces: Array.isArray(i18n.options.ns) ? i18n.options.ns : [i18n.options.ns || 'translation'],
    isInitialized: i18n.isInitialized,
    isLoaded: !!i18n.isInitialized,
  });
  
  // 更新i18n状态信息
  useEffect(() => {
    const interval = setInterval(() => {
      setResourceInfo({
        languages: i18n.languages,
        currentLanguage: i18n.language,
        namespaces: Array.isArray(i18n.options.ns) ? i18n.options.ns : [i18n.options.ns || 'translation'],
        isInitialized: i18n.isInitialized,
        isLoaded: !!i18n.isInitialized,
      });
    }, 1000);
    
    return () => clearInterval(interval);
  }, [i18n]);
  
  // 添加i18n事件监听器
  useEffect(() => {
    const handleLoaded = (lng: string, ns: string) => {
      console.log(`I18nTester: 语言资源加载成功 ${lng}/${ns}`);
      setResourceInfo(prev => ({
        ...prev,
        isLoaded: true
      }));
    };
    
    const handleFailedLoading = (lng: string, ns: string, msg: string) => {
      console.error(`I18nTester: 语言资源加载失败 ${lng}/${ns}: ${msg}`);
      setError(`加载语言 ${lng}/${ns} 失败: ${msg}`);
    };
    
    const handleLanguageChanged = (lng: string) => {
      console.log(`I18nTester: 语言已切换到 ${lng}`);
      setResourceInfo(prev => ({
        ...prev,
        currentLanguage: lng
      }));
    };
    
    i18n.on('loaded', handleLoaded);
    i18n.on('failedLoading', handleFailedLoading);
    i18n.on('languageChanged', handleLanguageChanged);
    
    return () => {
      i18n.off('loaded', handleLoaded);
      i18n.off('failedLoading', handleFailedLoading);
      i18n.off('languageChanged', handleLanguageChanged);
    };
  }, [i18n]);
  
  // 测试翻译键
  const testTranslation = () => {
    try {
      const result = t(translationKey);
      setTranslationResult(result);
      setError(null);
      
      // 添加到最近使用的键列表
      if (!recentKeys.includes(translationKey)) {
        setRecentKeys(prev => [translationKey, ...prev].slice(0, 10));
      }
    } catch (err) {
      console.error('翻译测试错误:', err);
      setError(`翻译键 "${translationKey}" 出错: ${err instanceof Error ? err.message : String(err)}`);
      setTranslationResult('');
    }
  };
  
  // 切换语言
  const toggleLanguage = () => {
    const newLang = i18n.language === 'en' ? 'zh' : 'en';
    try {
      i18n.changeLanguage(newLang);
      localStorage.setItem('i18nextLng', newLang);
    } catch (err) {
      console.error('切换语言错误:', err);
      setError(`切换到语言 ${newLang} 失败: ${err instanceof Error ? err.message : String(err)}`);
    }
  };
  
  // 使用某个最近使用的键 - 修改为普通函数，不是React Hook
  const handleRecentKeyClick = (key: string) => {
    setTranslationKey(key);
    // 使用setTimeout确保状态更新后再执行testTranslation
    setTimeout(testTranslation, 0);
  };
  
  // 重载当前语言资源
  const reloadResources = () => {
    const currentLng = i18n.language;
    i18n.reloadResources(currentLng)
      .then(() => {
        console.log(`资源重新加载成功: ${currentLng}`);
      })
      .catch((err: Error | unknown) => {
        console.error('资源重新加载失败:', err);
        setError(`重新加载语言 ${currentLng} 失败: ${err instanceof Error ? err.message : String(err)}`);
      });
  };
  
  return (
    <Paper sx={{ p: 3, maxWidth: 800, mx: 'auto', my: 4 }}>
      <Typography variant="h5" gutterBottom>
        国际化(i18n)测试工具
      </Typography>
      
      <Divider sx={{ my: 2 }} />
      
      {/* 状态信息 */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" gutterBottom>
          当前状态:
        </Typography>
        <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
          <Alert severity="info" sx={{ flexGrow: 1 }}>
            当前语言: <strong>{resourceInfo.currentLanguage}</strong>
          </Alert>
          <Alert severity={resourceInfo.isInitialized ? "success" : "warning"} sx={{ flexGrow: 1 }}>
            初始化状态: <strong>{resourceInfo.isInitialized ? '已完成' : '未完成'}</strong>
          </Alert>
        </Box>
      </Box>
      
      {/* 错误信息 */}
      {error && (
        <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}
      
      {/* 翻译测试 */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" gutterBottom>
          翻译键测试:
        </Typography>
        <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
          <TextField
            label="翻译键"
            value={translationKey}
            onChange={(e) => setTranslationKey(e.target.value)}
            fullWidth
            size="small"
          />
          <Button 
            variant="contained" 
            onClick={testTranslation}
            disabled={!translationKey}
          >
            测试
          </Button>
        </Box>
        
        {translationResult && (
          <Paper variant="outlined" sx={{ p: 2, backgroundColor: '#f5f5f5' }}>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              翻译结果:
            </Typography>
            <Typography variant="body1">
              {translationResult === translationKey ? (
                <span style={{ color: 'red' }}>
                  {`未找到翻译键 "${translationKey}"`}
                </span>
              ) : (
                translationResult
              )}
            </Typography>
          </Paper>
        )}
      </Box>
      
      {/* 操作按钮 */}
      <Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
        <Button 
          variant="outlined" 
          onClick={toggleLanguage}
        >
          切换到 {i18n.language === 'en' ? '中文' : 'English'}
        </Button>
        <Button 
          variant="outlined" 
          onClick={reloadResources}
        >
          重新加载资源
        </Button>
        <FormControlLabel
          control={
            <Switch 
              checked={showDebugInfo}
              onChange={(e) => setShowDebugInfo(e.target.checked)}
            />
          }
          label="显示调试信息"
        />
      </Box>
      
      {/* 最近使用的键 */}
      {recentKeys.length > 0 && (
        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle1" gutterBottom>
            最近使用的翻译键:
          </Typography>
          <List dense>
            {recentKeys.map((key, index) => (
              <ListItem 
                key={index} 
                button 
                onClick={() => handleRecentKeyClick(key)}
              >
                <ListItemText primary={key} />
              </ListItem>
            ))}
          </List>
        </Box>
      )}
      
      {/* 调试信息 */}
      {showDebugInfo && (
        <>
          <Divider sx={{ my: 2 }} />
          <Typography variant="subtitle1" gutterBottom>
            调试信息:
          </Typography>
          <pre style={{ backgroundColor: '#f5f5f5', padding: '8px', overflowX: 'auto' }}>
            {JSON.stringify(resourceInfo, null, 2)}
          </pre>
          
          <Typography variant="subtitle1" gutterBottom sx={{ mt: 2 }}>
            可用的命名空间:
          </Typography>
          <List dense>
            {resourceInfo.namespaces.map((ns: string, index: number) => (
              <ListItem key={index}>
                <ListItemText primary={ns} />
              </ListItem>
            ))}
          </List>
          
          <Typography variant="subtitle1" gutterBottom sx={{ mt: 2 }}>
            支持的语言:
          </Typography>
          <List dense>
            {resourceInfo.languages.map((lang: string, index: number) => (
              <ListItem key={index}>
                <ListItemText 
                  primary={lang} 
                  secondary={lang === resourceInfo.currentLanguage ? '(当前)' : ''} 
                />
              </ListItem>
            ))}
          </List>
        </>
      )}
    </Paper>
  );
};

export default I18nTester; 